<?php

namespace app\admin\model;

use think\Model;

class Category extends Model
{
    protected $field = true;

    protected static function init()
    {

        Category::beforeUpdate(function ($category) {
            //商品接收id
            $categoryId = $category->id;
            //处理商品属性
            $categoryData = input('post.');

            //处理商品推荐位
            db('rec_item')->where(array('value_type' => 2, 'value_id' => $categoryId))->delete();

            if (!empty($categoryData['recpos'])) {
                foreach ($categoryData['recpos'] as $k => $v) {
                    db('rec_item')->insert(['recpos_id' => $v, 'value_id' => $categoryId, 'value_type' => 2]);
                }
            } else {
                db('rec_item')->where(array('value_id' => $categoryId, 'value_type' => 2))->delete();
            }

        });

        Category::afterInsert(function ($category) {
            //接收表单数据
            $categoryData = input('post.');
            //商品接收id
            $categoryId = $category->id;

            //处理商品推荐位
            if (!empty($categoryData['recpos'])) {
                foreach ($categoryData['recpos'] as $k => $v) {
                    db('rec_item')->insert(['recpos_id' => $v, 'value_id' => $categoryId, 'value_type' => 2]);
                }
            } else {
                db('rec_item')->where(array('value_id' => $categoryId, 'value_type' => 2))->delete();
            }

        });

    }
}
